package com.yenroc.ho.resources;

import com.yenroc.ho.context.GlobalContext;
import com.yenroc.ho.transaction.GlobalTransactionInfo;
import com.yenroc.ho.transaction.GlobalTransactionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;

/**
 * @author： heyanpeng
 * @date： 2021/7/29
 */
@Service(value = "tkResourceProxy")
public class TkResourceProxy {

    private final GlobalContext globalContext;

    @Autowired
    public TkResourceProxy(GlobalContext globalContext){
        this.globalContext = globalContext;
    }

    public Connection proxyConnection(Connection connection) throws Throwable {
        GlobalTransactionInfo current = GlobalTransactionManager.getCurrent();
        try {
            return globalContext.getConnection(current.getTransactionId());
        } catch (Exception e) {
            GlobalConnection globalConnection = new GlobalConnection(connection, current);
            globalContext.setConnection(current.getTransactionId(), globalConnection);
            globalConnection.setAutoCommit(false);
            return globalConnection;
        }
    }
}
